class MyBlockingQueue{
    private int[] arr=null;
    private int size=0;
    private int head=0;
    private int tail=0;
    private Object locker=new Object();
    public MyBlockingQueue(int capacity){
        arr=new int[capacity];
    }
    public void put(int elem) throws InterruptedException{
        synchronized(locker){
        while(size>=arr.length){
            locker.wait();
        }
        arr[tail]=elem;
        tail++;
        if(tail>=arr.length){
            tail=0;
        }
        size++;
        locker.notify();
    }
    }
    public  int  take() throws InterruptedException{
        synchronized(locker){
        while(size==0){
            locker.wait();
        }
        int result = arr[head];
        head++;
        if(head>=arr.length){
            head=0;
        }
        size--;
        locker.notify();
            return result;
        }
    }
}
public class Demo32 {
public static void main(String[] args) throws InterruptedException {
    //基于我们自己的阻塞队列
    MyBlockingQueue queue = new MyBlockingQueue(1000);
    Thread producer=new Thread(()->{
        int count =0 ;
        try{
        while(true){
            queue.put(count);
            System.out.println("添加一个元素"+count);
            count++;
            Thread.sleep(1000);
        }
    }catch(InterruptedException e){
        e.printStackTrace();
    }
    });
    Thread consumer=new Thread(()->{
        try {
            while(true){
                System.out.println("消费一个元素"+queue.take());
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    producer.start();
    consumer.start();
    producer.join();
    consumer.join();
}

}
